<?php

namespace App\Models\Traits;

use App\Models\Archive;
use Conner\Tagging\Model\Tag;
use Illuminate\Support\Facades\Cache;

trait CategoryHotTags
{
    // 存放临时 tags
    protected $tags = [];

    // 缓存相关配置
    protected $cache_key = 'category_hot_tags_';
    protected $cache_expire_in_seconds = 65 * 60;

    public function getHotTags()
    {
        // 尝试从缓存中取出 cache_key 对应的数据。如果能取到，便直接返回数据。
        // 否则运行匿名函数中的代码来取出活跃用户数据，返回的同时做了缓存。
        return Cache::remember($this->cache_key . $this->id, $this->cache_expire_in_seconds, function(){
            return $this->calculateHotTags();
        });
    }

    private function calculateHotTags()
    {
        $tags = Tag::pluck('name');
        $counts = [];
        foreach ($tags as $tag) {
            $count = Archive::where('category_id', $this->id)->withAnyTag($tag)->count();
            if ($count > 0) {
                $counts[] = [
                    'tag' => $tag,
                    'count' => $count
                ];
            }
        }
        return collect($counts)->sortByDesc('count')->values();
    }
}
